package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.DictService;
import com.bootdo.common.utils.*;
import com.bootdo.oa.domain.NotifyDO;
import com.bootdo.oa.service.NotifyService;
import com.bootdo.system.dao.MyInviteDao;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.MonthPerformance;
import com.bootdo.system.domain.MyInviteDO;
import com.bootdo.system.domain.PayDO;
import com.bootdo.system.domain.PayDeatailsDO;
import com.bootdo.system.domain.PersonalDO;
import com.bootdo.system.domain.RebateDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.SuyongDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserRoleDO;
import com.bootdo.system.service.PayDeatailsService;
import com.bootdo.system.service.PayService;
import com.bootdo.system.service.RebateService;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.SuyongService;
import com.bootdo.system.service.UserOldService;
import com.bootdo.system.service.UserRoleService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.UserpicService;
import com.bootdo.system.vo.UserVO;

import cn.hutool.Hutool;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
	private String prefix = "system/user";
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	DictService dictService;
	@Autowired
	PayService payService;
	@Autowired
	UserRoleService userRoleService;
	@Autowired
	NotifyService notifyService;
	@Autowired
	RebateService rebateService;
	@Autowired
	UserOldService useroldService;
	@Autowired
	SuyongService suyongService;
	@Autowired
	UserpicService userpicService;
	@Autowired
	MyInviteDao myInviteDao;
	@Autowired
	PayDeatailsService  payDeatailsService;
	
	@ResponseBody
	@GetMapping("/test")
	String getA(){
		
		String a ="" + (char)29 +(char)86 + (char)66 + (char)1;
		return a;
	}


	@RequiresPermissions("sys:user:user")
	@GetMapping("")
	String user(Model model) {

		return prefix + "/user";
	}

	/**
	 * @Title: list
	 * @Description: TODO(遍历下级的方法)
	 * @return: PageUtils
	 * @date:2018年4月17日
	 */
	@SuppressWarnings("null")
	@GetMapping("/list")
	@ResponseBody
	PageUtils list(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		Object object = params.get("agencyRank");
		String obj = String.valueOf(object);
		Long userId = ShiroUtils.getUserId();
		int roleId = userRoleService.getByUserId(userId);
		if (roleId != Constant.ROLEADMIN_ID) {
			params.put("myupper", userId);
		}
		Query query = new Query(params);
		int count;
		List<UserDO> oldUserList = null;
		if (obj.equals("4")) {
			oldUserList = useroldService.islistUser(query);
			for (UserDO userDO : oldUserList) {
				if (userDO.getMyupper() == 0) {
					userDO.setPname("速用");
				} else {
					userDO.setPname(useroldService.get(userDO.getMyupper()).getCompanyName());
				}
				SuyongDO suyongDO = suyongService.get(userDO.getId());
				if (suyongDO != null) {
					//userDO.setLiveAddress(suyongDO.getLiveAddress());
					userDO.setStatus(suyongDO.getStatus());
				}

			}
			count = useroldService.iscount(params);
		} else if (obj.equals("5")) {
			List<UserDO> users = new ArrayList<>();
			List<MyInviteDO> list = myInviteDao.get(userId);
			for (MyInviteDO myInviteDO : list) {
				UserDO userDO = useroldService.get(myInviteDO.getInviteId());
				if (userDO.getMyupper() == 0) {
					userDO.setPname("速用");
				} else {
					userDO.setPname(useroldService.get(userDO.getMyupper()).getCompanyName());
				}
				users.add(userDO);
			}
			Map<String, Object> map = new HashMap<>();
			map.put("userId", userId);
			Query Query = new Query(map);
			count = myInviteDao.count(Query);
			PageUtils pageUtil = new PageUtils(users, count);
			return pageUtil;

		}
		else {
			oldUserList = useroldService.listUser(query);
			for (UserDO userDO : oldUserList) {
				if (userDO.getMyupper() == 0) {
					userDO.setPname("速用");
				} else {

					userDO.setPname(useroldService.get(userDO.getMyupper()).getCompanyName());
				}
				SuyongDO suyongDO = suyongService.get(userDO.getId());
				if (suyongDO != null) {
					userDO.setStatus(suyongDO.getStatus());
					//userDO.setLiveAddress(suyongDO.getLiveAddress());
				}

			}
			count = useroldService.count(query);
		}
		PageUtils pageUtil = new PageUtils(oldUserList, count);
		return pageUtil;
	}

	/**
	 * @Title: list
	 * @Description: TODO(移动端我的客户接口)
	 * @author: lzy
	 * @date: 2018年5月25日 上午9:10:21
	 */
	@GetMapping("/applist")
	@ResponseBody
	PageUtils applist(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		Long userId = ShiroUtils.getUserId();
		int roleId = userRoleService.getByUserId(userId);
		if (roleId != Constant.ROLEADMIN_ID) {
			params.put("myupper", userId);
		}
		Query query = new Query(params);
		int count;
		List<UserDO> oldUserList = null;
		oldUserList = useroldService.islistUser(query);
		for (UserDO userDO : oldUserList) {
			if (userpicService.getUrl(userDO.getId()) == null) {
				userDO.setUserPic(Constant.USER_PIC);// 设置默认头像
			} else {
				userDO.setUserPic(userpicService.getUrl(userDO.getId()));
			}
			SuyongDO suyongDO = suyongService.get(userDO.getId());
			if (suyongDO != null && suyongDO.getFirstlogin() == 1) {
				userDO.setCity(suyongDO.getProvince() + suyongDO.getCity() + suyongDO.getDistrict()
						+ suyongDO.getLiveAddress());
				userDO.setStatus(suyongDO.getStatus());
				userDO.setWyzAllmoney(suyongDO.getWyzAllmoney());
			} else {
				userDO.setCity("暂无");
				userDO.setWyzAllmoney(userDO.getWyzMoney());
			}

		}
		count = useroldService.iscount(params);
		PageUtils pageUtil = new PageUtils(oldUserList, count);
		return pageUtil;
	}

	/**
	 * @Title: list
	 * @Description: TODO(移动端我的代理接口)
	 * @author: lzy
	 * @date: 2018年5月25日 上午9:10:21
	 */
	@GetMapping("/agencylist")
	@ResponseBody
	PageUtils agencylist(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		Long userId = ShiroUtils.getUserId();
		int roleId = userRoleService.getByUserId(userId);
		if (roleId != Constant.ROLEADMIN_ID) {
			params.put("myupper", userId);
		}
		Query query = new Query(params);
		int count;
		List<UserDO> oldUserList = null;
		oldUserList = useroldService.islistAgency(query);
		for (UserDO userDO : oldUserList) {
			if (userpicService.getUrl(userDO.getId()) == null) {
				userDO.setUserPic(Constant.USER_PIC);// 设置默认头像
			} else {
				userDO.setUserPic(userpicService.getUrl(userDO.getId()));
			}
			SuyongDO suyongDO = suyongService.get(userDO.getId());
			if (suyongDO != null && suyongDO.getFirstlogin() == 1) {
				userDO.setCity(suyongDO.getProvince() + suyongDO.getCity() + suyongDO.getDistrict()
						+ suyongDO.getLiveAddress());
				userDO.setStatus(suyongDO.getStatus());
				userDO.setWyzAllmoney(suyongDO.getWyzAllmoney());
			} else {
				userDO.setCity("暂无");
				userDO.setWyzAllmoney(userDO.getWyzMoney());
			}

		}
		count = useroldService.iscount(params);
		PageUtils pageUtil = new PageUtils(oldUserList, count);
		return pageUtil;
	}

	/**
	 * @Title: paylists
	 * @Description: TODO(所有充值记录的查询方法)
	 * @author: lzy
	 * @date: 2018年5月9日 上午10:43:48
	 */
	@GetMapping("/paylists")
	@ResponseBody
	PageUtils paylists(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		Query query = new Query(params);
		List<PayDO> list = payService.list(query);
		int total = payService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	/**
	 * @Title: payAll
	 * @Description: TODO(舔砖查询说有记录的方法)
	 * @author: lzy
	 * @date: 2018年5月9日 上午10:43:48
	 */
	@GetMapping("/payAll")
	String payAll() {
		// 查询列表数据

		return prefix + "/payall";
	}

	@RequiresPermissions("sys:user:add")
	@GetMapping("/add")
	String add(Model model) {
		/*
		 * List<RoleDO> roles = roleService.list(); model.addAttribute("roles",
		 * roles);
		 */
		return prefix + "/add";
	}

	/**
	 * @Title: payNotes
	 * @Description: TODO(跳转充值记录页面)
	 * @return: String
	 * @author:liuziyu
	 * @date:2018年4月20日
	 */
	@GetMapping("/payNotes")
	String payNotes(Model model) {
		return prefix + "/payNotes";
	}
	
	
	/**
	 * @Title: payNotes
	 * @Description: TODO(跳转充值记录页面)
	 * @return: String
	 * @author:liuziyu
	 * @date:2018年4月20日
	 */
	@GetMapping("/payDetails")
	String payDetails(Model model) {
		return prefix + "/payDetails";
	}
	
	

	/**
	 * @Title: alipay
	 * @Description: TODO(跳转支付宝支付界面)
	 * @return: String
	 * @author:liuziyu
	 * @date:2018年4月20日
	 */
	@GetMapping("/alipay")
	String alipay(Model model) {
		/*
		 * List<RoleDO> roles = roleService.list(); model.addAttribute("roles",
		 * roles);
		 */
		return "/alipay/alipay";
	}

	@RequiresPermissions("sys:user:edit")
	@GetMapping("/edit/{id}")
	String edit(Model model, @PathVariable("id") Long id) {
		UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);

		return prefix + "/edit";
	}

	/**
	 * @Title: pay
	 * @Description: TODO(代理充值跳转页面的方法)
	 * @return: String
	 * @author:liuziyu
	 * @date:2018年4月19日
	 */
	@RequiresPermissions("sys:user:pay")
	@GetMapping("/pay/{id}")
	String pay(Model model, @PathVariable("id") Long id) {
		if (id >= Constant.SQL_NUMBER) {
			UserDO userDO = userService.get(id);
			if (userDO.getAgencyRank() == Constant.AGENT_ONE) {
				userDO.setDeptName("一级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATEONE));
			} else if (userDO.getAgencyRank() == Constant.AGENT_TWO) {
				userDO.setDeptName("二级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATETWO));
			} else if (userDO.getAgencyRank() == Constant.AGENT_THREE) {
				userDO.setDeptName("三级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATETHREE));
			} else {
				userDO.setDeptName("客户");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATEUSER));
			}
			model.addAttribute("user", userDO);

			return prefix + "/pay";
		} else {
			UserDO userDO = useroldService.get(id);
			Long agencyRank = null;
			try {
				agencyRank = userDO.getAgencyRank();
			} catch (Exception e) {

			}

			if (agencyRank == 0) {
				userDO.setDeptName("客户");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATEUSER));
				model.addAttribute("user", userDO);

				return prefix + "/pay";
			}
			if (agencyRank == Constant.AGENT_ONE) {
				userDO.setDeptName("一级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATEONE));
			} else if (agencyRank == Constant.AGENT_TWO) {
				userDO.setDeptName("二级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATETWO));
			} else if (agencyRank == Constant.AGENT_THREE) {
				userDO.setDeptName("三级代理");
				model.addAttribute("rebate", dictService.getValue(Constant.DIC_REBATETHREE));
			}
			model.addAttribute("user", userDO);

			return prefix + "/pay";
		}

	}

	/**
	 * @Title: paylist
	 * @Description: TODO(充值记录的查询方法)
	 * @return: PageUtils
	 * @author:liuziyu
	 * @date:2018年4月19日
	 */
	@GetMapping("/paylist")
	@ResponseBody
	PageUtils paylist(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		params.put("userId", ShiroUtils.getUserId());
		Query query = new Query(params);
		List<PayDO> list = payService.list(query);
		int total = payService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	/**
	 * @Title: agentPay
	 * @Description: TODO(代理充值)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年4月19日
	 */
	/* @RequiresPermissions("sys:user:agentpay") */
	@PostMapping("/agentPay")
	@ResponseBody
	@Transactional
	R agentPay(Model model, Long id, Long amount) {
			// 当前充值用户速用币增加
		    UserDO user = useroldService.get(id);
			long money = user.getWyzMoney() + amount;
			user.setId(id);
			user.setWyzMoney(money);
			// 上级当前速用币减少，总速用币不会减少
			UserDO parent= useroldService.get(getUserId());
			long Pmoney = parent.getWyzMoney() - amount;
			parent.setId(ShiroUtils.getUserId());
			parent.setWyzMoney(Pmoney);
			int updateUser = useroldService.update(user);
			int updateParent = useroldService.update(parent);
			if(updateUser == 1 && updateParent == 1){
				// 充值记录
				PayDO pay = new PayDO();
				pay.setUserId(getUserId());
				pay.setPayer(parent.getCompanyName());
				pay.setPayee(user.getCompanyName());
				pay.setPayeeId(id);
				pay.setPayment(1);
				pay.setPaymoney(amount);
				pay.setPayTime(new Date());
				//速用币明细表支入记录开始
				payDeatailsForSupport(id, amount,money);
				//速用币明细表支出记录开始
				payDeatailsForExpend(getUserId(),amount,Pmoney);
				int paySave = payService.save(pay);
				HashMap<String, Object> hashMap = new HashMap<>();
				hashMap.put("userId",id);
				int sum = payDeatailsService.sum(hashMap);
				MyInviteDO myInviteDO = myInviteDao.getSign(id);
				if(myInviteDO != null){
					if(sum>=Constant.REGISTER_COIN && myInviteDO.getSign()==0){
						//邀请表开始
						MyInviteDO invite = new MyInviteDO();
						invite.setInviteId(id);
						invite.setSign(1);
						myInviteDao.update(invite);
						//修改邀请人的信息
						Long userId = myInviteDO.getUserId();
						long wyzMoney = useroldService.get(userId).getWyzMoney()+Constant.REGISTER_SEND;
						UserDO userDO = new UserDO();
						userDO.setId(userId);
						userDO.setWyzMoney(wyzMoney);
						useroldService.update(userDO);
						//累计充值送币开始
						saveInviteForSupport(userId, Constant.REGISTER_SEND, wyzMoney);
						
						
					}
				}
	
				if (paySave == 1) {
					return R.ok("充值成功");
				} else {
					return R.ok("网络异常");
				}
			}else {
				return R.error("网络异常");
			}
	
		
	

	}
	
	
	

	/**
	 * @Title: agentPay
	 * @Description: TODO(预存代理充值的方法)
	 * @author: lzy
	 * @date: 2018年5月7日 下午5:36:01
	 */
	@Transactional
	@PostMapping("/agenterPay")
	@ResponseBody
	R agenterPay(Integer amount, Integer agent, Long id, String phone) {
		if (phone != null && id == null) {
			Map<String, Object> map = new HashMap<>();
			map.put("phone", phone);
			List<UserDO> oldlist = useroldService.list(map);
			if (oldlist.size() > 0) {
				Long userId = oldlist.get(0).getId();
				id = userId;
			} else {
				return R.error("手机号码不存在或者输入有误");
			}

		}
		String one = dictService.getValue(Constant.DIC_MONEYONE);// 预存一级代理所需的速用币
		String two = dictService.getValue(Constant.DIC_MONEYTWO);// 预存二级代理所需的速用币
		String three = dictService.getValue(Constant.DIC_MONEYTHREE);// 预存三级代理所需的速用币
		UserDO user = userService.get(id);
		if (agent == null) {
			return R.error("请选择代理级别");

		} else if (agent == (Constant.AGENT_ONE)) {
			if (amount >= Integer.parseInt(one)) {
				// 当前充值用户速用币增加
				UserDO parent = userService.get(getUserId()); //操作用户
				String name = user.getCompanyName();// 充值用户名
				long money = user.getWyzMoney() + amount;
				List<Long> roleIds = new ArrayList<Long>();
				roleIds.add((long) Constant.ROLEAGENT_ID);
				// 代理级别是'22'代表拥有设置一级代理的权限的二级
				if(parent.getAgencyRank() == Constant.TWO_ADMIN){
					user.setMyupper(getUserId());
				}else {
					user.setMyupper(Constant.SQL_NUMBER);// 升级一级代理上级变为速用
				}
				user.setId(id);
				user.setRoleIds(roleIds);
				user.setAgencyRank((long) Constant.AGENT_ONE);
				user.setAuthNo(DateUtils.getOrderIdByTime());// 生成授权证书编号
				user.setWyzMoney(money);

				// 操作用户当前速用币减少，总速用币不会减少
				long Pmoney = parent.getWyzMoney() - amount;
				parent.setId(getUserId());
				parent.setWyzMoney(Pmoney);

				// 通知升级为一级代理的用户
				NotifyDO notify = new NotifyDO();
				notify.setCreateBy(Constant.SQL_NUMBER);
				notify.setTitle("升级通知");
				if(parent.getAgencyRank() == Constant.TWO_ADMIN){
					notify.setContent("恭喜升级为一级代理.你的上级现在为("+parent.getCompanyName()+")。一级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATEONE)
					+ "的充值返利！");
					notify.setRemarks("需要充值请直接联系"+parent.getCompanyName()+"("+parent.getPhone()+")");
				}else {
					notify.setContent("恭喜升级为一级代理.你的上级现在为(速用科技)。一级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATEONE)
					+ "的充值返利！");
					notify.setRemarks("需要充值请直接联系速用科技("+Constant.SUYONG_PHONE+")");
				}
				Long[] userIds = { id };
				notify.setUserIds(userIds);
				notifyService.save(notify);

				// 通知返利开始
				NotifyDO notify1 = new NotifyDO();
				notify1.setTitle("返利通知");
				notify1.setContent("(" + user.getCompanyName() + ")升级为 一級代理!请及时处理");
				notify1.setCreateDate(new Date());
				notify1.setCreateBy(Constant.SQL_NUMBER);
				notify1.setRemarks("预存升级一级代理，返利明细请在后台操作");
				if(parent.getAgencyRank() == Constant.TWO_ADMIN){
					Long[] userIds1 = {getUserId()};
					notify1.setUserIds(userIds1);
				}else{
					Long[] userIds1 = { Constant.SQL_NUMBER };
					notify1.setUserIds(userIds1);
				}
				notifyService.save(notify1);

				// 充值记录开始
				PayDO pay = new PayDO();
				pay.setUserId(getUserId());
				pay.setPayer(parent.getCompanyName());
				pay.setPayee(name);
				pay.setPayeeId(id);
				pay.setPayment(0);// 1.代理充值 2.本人充值 0.预存充值
				pay.setPaymoney(amount);
				pay.setPayTime(new Date());
				payService.save(pay);
				//预存充代理充值减少
				savaDeatailsForExpend(getUserId(),(long)amount,Pmoney);
				//预存充代理充值增加
				savaDeatailsForSupport(id,(long)amount,money);
				// 充值记录结束
				userService.updateForAgenterPay(user);// 更新当前需要充值的用户
				userService.updateForAgenterPay(parent);// 更新操作用户
				//升级代理邀请用户自动转移  开始
				if(myInviteDao.get(id).size() > 0){
				      autoAgent(id, name);
				}
				//升级代理邀请用户自动转移  结束
				return R.ok("充值一级代理成功！");
			} else {
				return R.error("一级代理预存最低需要充值" + one + "速用币");
			}
		} else if (agent == Constant.AGENT_TWO) {
			if (amount >= Integer.parseInt(two)) {
				// 当前充值用户速用币增加
				String name = user.getCompanyName();// 充值用户
				UserDO upperUser;
				if (user.getMyupper() == 0) {
					upperUser = userService.get(getUserId());// 旧系统存在上级为0的情况 只有管理员能够看到
				} else {
					upperUser = userService.get(user.getMyupper());// 需返利纯利润50%的用户
				}

				long money = user.getWyzMoney() + amount;
				List<Long> roleIds = new ArrayList<Long>();
				roleIds.add((long) Constant.ROLEAGENT_ID);
				user.setMyupper(ShiroUtils.getUserId());
				user.setId(id);
				user.setRoleIds(roleIds);
				user.setAgencyRank((long) Constant.AGENT_TWO);
				user.setAuthNo(DateUtils.getOrderIdByTime());// 生成授权证书编号
				user.setWyzMoney(money);

				// 操作用户速用币减少，总速用币不会减少
				UserDO parent = userService.get(getUserId());
				long Pmoney = parent.getWyzMoney() - amount;
				parent.setId(ShiroUtils.getUserId());
				parent.setWyzMoney(Pmoney);

				// 通知升级为二级代理的用户
				NotifyDO notify = new NotifyDO();
				notify.setCreateBy(Constant.SQL_NUMBER);
				notify.setTitle("升级通知");
				if(parent.getId() == Constant.SQL_NUMBER){
					notify.setContent("恭喜升级为二级代理.你的上级现在为(" + parent.getCompanyName() + "),联系电话(" + Constant.SUYONG_PHONE
					+ ")。二级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATETWO) + "的充值折扣！");
				}else {
					notify.setContent("恭喜升级为二级代理.你的上级现在为(" + parent.getCompanyName() + "),联系电话(" + parent.getPhone()
					+ ")。二级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATETWO) + "的充值折扣！");
				}
				notify.setRemarks("需要充值请联系你的上级");
				Long[] userIds = { id };
				notify.setUserIds(userIds);
				notifyService.save(notify);

				float one1 = Float.parseFloat(dictService.getValue(Constant.DIC_REBATEONE));
				float one2 = Float.parseFloat(dictService.getValue(Constant.DIC_REBATETWO));
				if (phone != null || getUserId() == Constant.SQL_NUMBER) {

					// 通知返利开始
					NotifyDO notify1 = new NotifyDO();
					notify1.setTitle("返利通知");
					notify1.setContent("(" + user.getCompanyName() + ")升级为 二级代理(" + upperUser.getCompanyName() + ")获得"
							+ (int) (amount * one2 - amount * one1) * 0.5 + "元充值额返利!请及时处理");
					notify1.setCreateDate(new Date());
					notify1.setCreateBy(Constant.SQL_NUMBER);
					notify1.setRemarks("详情请查看图表管理——>返利明细");
					Long[] userIds1 = { ShiroUtils.getUserId() };
					notify1.setUserIds(userIds1);
					notifyService.save(notify1);

					// 返利明细开始

					RebateDO rebate = new RebateDO();
					rebate.setRebaters(upperUser.getCompanyName());
					rebate.setCourse("(" + user.getCompanyName() + ")升级为 二级代理(" + upperUser.getCompanyName() + ")获得"
							+ (int) (amount * one2 - amount * one1) * 0.5 + "元充值额返利!计算规则为纯利润的50%:如：" + amount
							+ "(充值速用币)x" + one2 + "(二级充值折扣)-" + amount + "(充值速用币)x" + one1 + "(一级充值折扣)");
					rebate.setGmtCreate(new Date());
					rebate.setUserId(ShiroUtils.getUserId());
					rebate.setRemark("仅供参考，返利请以实际操作为准");
					rebate.setRebate(one2 + "");
					rebate.setMoney((int) amount);
					rebate.setRmoney((int) (((amount * one2 - amount * one1) * 0.5)));
					rebateService.save(rebate);
					// 返利明细结束
				} else {
					// 通知返利开始
					NotifyDO notify1 = new NotifyDO();
					notify1.setTitle("返利通知");
					notify1.setContent("(" + user.getCompanyName() + ")升级为 二级代理,该客户为你的直接下级无需返利");
					notify1.setCreateDate(new Date());
					notify1.setCreateBy(Constant.SQL_NUMBER);
					notify1.setRemarks("该记录不计入返利明细表中！");
					Long[] userIds1 = { ShiroUtils.getUserId() };
					notify1.setUserIds(userIds1);
					notifyService.save(notify1);
				}

				userService.updateForAgenterPay(user);
				userService.updateForAgenterPay(parent);

				// 充值记录开始
				PayDO pay = new PayDO();
				pay.setUserId(getUserId());
				pay.setPayer(parent.getCompanyName());
				pay.setPayee(name);
				pay.setPayeeId(id);
				pay.setPayment(0);// 1.代理充值 2.本人充值 0.预存充值
				pay.setPaymoney(amount);
				pay.setPayTime(new Date());
				payService.save(pay);
				// 充值记录结束
				//预存充代理充值减少
				savaDeatailsForExpend(getUserId(),(long)amount,Pmoney);
				//预存充代理充值增加
				savaDeatailsForSupport(id,(long)amount,money);
				if(myInviteDao.get(id).size() > 0){
				      autoAgent(id, name);
				}
				return R.ok("充值二级代理成功！");
			} else {
				return R.error("二级代理预存最低需要充值" + two + "速用币");
			}

		} else if (agent == Constant.AGENT_THREE) {
			if (amount >= Integer.parseInt(three)) {
				// 当前充值用户速用币增加

				String name = user.getCompanyName();// 充值用户
				UserDO upperUser;
				if (user.getMyupper() == 0) {
					upperUser = userService.get(ShiroUtils.getUserId());// 旧系统存在上级为0的情况
																		// 只有管理员能够看到
				} else {
					upperUser = userService.get(user.getMyupper());// 需返利纯利润50%的用户
				}

				long money = user.getWyzMoney() + amount;
				List<Long> roleIds = new ArrayList<Long>();
				roleIds.add((long) Constant.ROLEAGENT_ID);
				user.setMyupper(ShiroUtils.getUserId());
				user.setId(id);
				user.setRoleIds(roleIds);
				user.setAgencyRank((long) Constant.AGENT_THREE);
				user.setAuthNo(DateUtils.getOrderIdByTime());// 生成授权证书
				user.setWyzMoney(money);

				// 操作用户速用币减少，总速用币不会减少
				UserDO parent = userService.get(ShiroUtils.getUserId());
				long Pmoney = parent.getWyzMoney() - amount;
				parent.setId(ShiroUtils.getUserId());
				parent.setWyzMoney(Pmoney);

				// 通知升级为三级级代理的用户
				NotifyDO notify = new NotifyDO();
				notify.setCreateBy(ShiroUtils.getUserId());
				notify.setTitle("升级通知");
				if(parent.getId() == Constant.SQL_NUMBER){
					notify.setContent("恭喜升级为 三级代理.你的上级现在为(" + parent.getCompanyName() + "),联系电话(" + Constant.SUYONG_PHONE
					+ ")。三级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATETHREE) + "的充值折扣！");
				}else {
					notify.setContent("恭喜升级为 三级代理.你的上级现在为(" + parent.getCompanyName() + "),联系电话(" + parent.getPhone()
					+ ")。三级代理速用币充值享有" + dictService.getValue(Constant.DIC_REBATETHREE) + "的充值折扣！");
				}
				notify.setRemarks("需要充值请联系你的上级");
				Long[] userIds = { id };
				notify.setUserIds(userIds);
				notifyService.save(notify);
				float one1 = Float.parseFloat(dictService.getValue(Constant.DIC_REBATEONE));
				float one2 = Float.parseFloat(dictService.getValue(Constant.DIC_REBATETWO));
				float one3 = Float.parseFloat(dictService.getValue(Constant.DIC_REBATETHREE));
				if (phone != null || getUserId() == Constant.SQL_NUMBER) {

					// 通知返利开始
					NotifyDO notify1 = new NotifyDO();
					notify1.setTitle("返利通知");
					if (getUser().getAgencyRank() == Constant.AGENT_ONE) {
						notify1.setContent("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName()
								+ ")获得" + (int) (amount * one3 - amount * one1) * 0.5 + "元充值额返利!请及时处理");
					} else if (getUser().getAgencyRank() == Constant.AGENT_TWO) {
						notify1.setContent("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName()
								+ ")获得" + (int) (amount * one3 - amount * one2) * 0.5 + "元充值额返利!请及时处理");
					} else if (getUser().getAgencyRank() == 11) {
						notify1.setContent("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName()
								+ ")获得" + (int) (amount * one3 - amount * one1) * 0.5 + "元充值额返利!请及时处理!管理员返利按一级代理计算");
					}

					notify1.setCreateDate(new Date());
					notify1.setCreateBy(Constant.SQL_NUMBER);
					notify1.setRemarks("详情请查看图表管理——>返利明细");
					Long[] userIds1 = { ShiroUtils.getUserId() };
					notify1.setUserIds(userIds1);
					notifyService.save(notify1);

					// 返利明细开始

					RebateDO rebate = new RebateDO();
					rebate.setRebaters(upperUser.getCompanyName());
					if (getUser().getAgencyRank() == Constant.AGENT_ONE) {
						rebate.setCourse("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName() + ")获得"
								+ (int) (amount * one3 - amount * one1) * 0.5 + "元充值额返利!计算规则为纯利润的50%:如：" + amount
								+ "(充值速用币)x" + one3 + "(三级充值折扣)-" + amount + "(充值速用币)x" + one1 + "(一级充值折扣)");
						rebate.setRmoney((int) ((amount * one3 - amount * one1) * 0.5));
					} else if (getUser().getAgencyRank() == Constant.AGENT_TWO) {
						rebate.setCourse("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName() + ")获得"
								+ (int) (amount * one3 - amount * one2) * 0.5 + "元充值额返利!计算规则为纯利润的50%:如：" + amount
								+ "(充值速用币)x" + one3 + "(三级充值折扣)-" + amount + "(充值速用币)x" + one2 + "(二级充值折扣)");
						rebate.setRmoney((int) ((amount * one3 - amount * one2) * 0.5));
					} else if (getUser().getAgencyRank() == 11) {
						rebate.setCourse("(" + user.getCompanyName() + ")升级为 三级代理(" + upperUser.getCompanyName() + ")获得"
								+ (int) (amount * one3 - amount * one1) * 0.5 + "元充值额返利!(管理员充值返利按一级代理计算)计算规则为纯利润的50%:如："
								+ amount + "(充值速用币)x" + one3 + "(三级充值折扣)-" + amount + "(充值速用币)x" + one1 + "(一级充值折扣)");
						rebate.setRmoney((int) ((amount * one3 - amount * one1) * 0.5));
					}

					rebate.setGmtCreate(new Date());
					rebate.setUserId(ShiroUtils.getUserId());
					rebate.setRemark("仅供参考，返利请以实际操作为准");
					rebate.setRebate(one3 + "");
					rebate.setMoney((int) amount);
					rebateService.save(rebate);
					// 返利明细结束
				} else {
					// 通知返利开始
					NotifyDO notify1 = new NotifyDO();
					notify1.setTitle("返利通知");
					notify1.setContent("(" + user.getCompanyName() + ")升级为 三级代理,该客户为你的直接下级无需返利");
					notify1.setCreateDate(new Date());
					notify1.setCreateBy(Constant.SQL_NUMBER);
					notify1.setRemarks("该记录不计入返利明细表中！");
					Long[] userIds1 = { ShiroUtils.getUserId() };
					notify1.setUserIds(userIds1);
					notifyService.save(notify1);
				}

				userService.updateForAgenterPay(user);
				userService.updateForAgenterPay(parent);

				// 充值记录开始
				PayDO pay = new PayDO();
				pay.setUserId(getUserId());
				pay.setPayer(parent.getCompanyName());
				pay.setPayee(name);
				pay.setPayeeId(id);
				pay.setPayment(0);// 1.代理充值 2.本人充值 0.预存充值
				pay.setPaymoney(amount);
				pay.setPayTime(new Date());
				payService.save(pay);
				// 充值记录结束
				//预存充代理充值减少
				savaDeatailsForExpend(getUserId(),(long)amount,Pmoney);
				//预存充代理充值增加
				savaDeatailsForSupport(id,(long)amount,money);
				
				//升级代理邀请用户自动转移  开始
				if(myInviteDao.get(id).size() > 0){
				      autoAgent(id, name);
				}
				//升级代理邀请用户自动转移  结束
				

				return R.ok("充值三级代理成功！");
			} else {
				return R.error("三级代理预存最低需要充值" + three + "速用币");
			}
		} else {
			return R.error("充值失败");
		}

	}

	/**
	 * @Title: check
	 * @Description: TODO(检查代理升级的方法)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年4月17日
	 */
	int check(Long allmoney, DictService dictService) {

		int value = Integer.parseInt(dictService.getValue(Constant.DIC_MONEYONE));// 一级代理充值额度

		int value2 = Integer.parseInt(dictService.getValue(Constant.DIC_MONEYTWO));// 二级代理充值额度

		int value3 = Integer.parseInt(dictService.getValue(Constant.DIC_MONEYTHREE));// 三级代理充值额度

		if (allmoney >= value) {
			return 1;
		} else if (allmoney >= value2) {
			return 2;
		} else if (allmoney >= value3) {
			return 3;
		} else {
			return 0;
		}

	}

	/**
	 * @Title: rebate
	 * @Description: TODO(跳转返利明细的方法)
	 * @author: lzy
	 * @date: 2018年5月2日 上午9:30:41
	 */
	@GetMapping("/rebate")
	String rebate() {

		return prefix + "/rebate";
	}

	/**
	 * @Title: reply
	 * @Description: TODO(跳转返利状态修改界面)
	 * @author: lzy
	 * @date: 2018年5月2日 上午10:51:56
	 */
	@Transactional
	@GetMapping("/read/{id}")
	String reply(@PathVariable("id") Long id, Model model) {
		model.addAttribute("id", id);
		RebateDO rebate = new RebateDO();
		rebate.setId(id);
		rebate.setStatus(1);
		rebateService.update(rebate);
		RebateDO rebateDO = rebateService.get(id);
		model.addAttribute("rebate", rebateDO);
		return prefix + "/reply";
	}

	/**
	 * @Title: rebatelist
	 * @Description: TODO(遍历返利明细的方法)
	 * @author: lzy
	 * @date: 2018年5月2日 下午1:41:22
	 */
	@GetMapping("/rebatelist")
	@ResponseBody
	PageUtils rebatelist(@RequestParam Map<String, Object> params, Model model) {
		// 查询列表数据
		Long Id = ShiroUtils.getUserId();
		int roleId = userRoleService.getByUserId(Id);
		if (roleId != Constant.ROLEADMIN_ID) {
			params.put("userId", Id);
		}
		Query query = new Query(params);
		List<RebateDO> list = rebateService.list(query);
		int total = rebateService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	/**
	 * @Title: batchRemoveRebate
	 * @Description: TODO(批量删除返利记录)
	 * @author: lzy
	 * @date: 2018年5月4日 下午3:24:15
	 */
	@PostMapping("/batchRemoveRebate")
	@ResponseBody
	R batchRemoveRebate(@RequestParam("ids[]") Long[] userIds) {
		int r = rebateService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:add")
	@PostMapping("/save")
	@ResponseBody
	R save(UserDO user) {
		user.setPassword(MD5Utils.encrypt(user.getPhone(), user.getPassword()));
		if (userService.save(user) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:add")
	@PostMapping("/saveAdmin")
	@ResponseBody
	R saveAdmin(UserDO user) {
		if (userService.saveAdmin(user) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:edit")
	@PostMapping("/update")
	@ResponseBody
	R update(UserDO user) {
		if (userService.update(user) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:edit")
	@PostMapping("/updatePeronal")
	@ResponseBody
	R updatePeronal(UserDO user) {
		if (userService.updatePersonal(user) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:remove")
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		if (userService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:batchRemove")
	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * @Title: paybatchRemove
	 * @Description: TODO(批量删除充值记录)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年4月19日
	 */
	@PostMapping("/paybatchRemove")
	@ResponseBody
	R paybatchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = payService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/noexit")
	@ResponseBody
	boolean exit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		boolean noexit = userService.noexit(params);
		return noexit;
	}

	@PostMapping("/exit")
	@ResponseBody
	boolean noexit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return userService.exit(params);
	}

	@PostMapping("/moneyExit")
	@ResponseBody
	boolean moneyExit(@RequestParam Long amount) {
		UserDO user = userService.get(ShiroUtils.getUserId());
		long money = user.getWyzMoney();
		if (money >= amount) {
			return true;
		} else {
			return false;
		}

	}

	@RequiresPermissions("sys:user:resetPwd")
	@Log("请求更改用户密码")
	@GetMapping("/resetPwd/{id}")
	String resetPwd(@PathVariable("id") Long id, Model model) {
		UserDO userDO = useroldService.get(id);
		model.addAttribute("user", userDO);
		return prefix + "/reset_pwd";
	}

	/**
	 * @Title: setAgent
	 * @Description: TODO(跳转预存设置代理的方法)
	 * @author: lzy
	 * @date: 2018年5月7日 下午4:23:24
	 */
	/* @RequiresPermissions("sys:user:setAgent") */
	@GetMapping("/setAgent/{id}")
	String setAgent(@PathVariable("id") Long id, Model model) {
		model.addAttribute("id", id);
		model.addAttribute("agent", getUser().getAgencyRank());
		return prefix + "/setagent";
	}

	/**
	 * @Title: setAgentNo
	 * @Description: TODO(跳转非直接预存代理设置界面)
	 * @author: lzy
	 * @date: 2018年5月8日 上午11:51:22
	 */
	/* @RequiresPermissions("sys:user:setAgent") */
	@GetMapping("/setAgentNo")
	String setAgentNo(Long userId, Model model) {
		/* model.addAttribute("userId", userId); */
		model.addAttribute("agent", getUser().getAgencyRank());
		return prefix + "/setagentno";
	}

	@PostMapping("/resetPwd")
	@ResponseBody
	R resetPwd(UserVO userVO) {
		try {
			userService.resetPwd(userVO, getUser());
			return R.ok();
		} catch (Exception e) {
			return R.error(1, e.getMessage());
		}

	}

	@RequiresPermissions("sys:user:resetPwd")
	@PostMapping("/adminResetPwd")
	@ResponseBody
	R adminResetPwd(UserVO userVO) {

		try {
			useroldService.adminResetPwd(userVO);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return R.error("网络异常");
		}
	   return R.ok();
		

	}

	@GetMapping("/tree")
	@ResponseBody
	public Tree<DeptDO> tree() {
		Tree<DeptDO> tree = new Tree<DeptDO>();
		tree = userService.getTree();
		return tree;
	}

	@GetMapping("/treeView")
	String treeView() {
		return prefix + "/userTree";
	}

	/**
	 * @Title: mypersonal
	 * @Description: TODO(跳转个人自资料界面的方法)
	 * @author: lzy
	 * @date: 2018年5月7日 下午2:41:57
	 */
	@GetMapping("/mypersonal")
	String mypersonal() {
		return prefix + "/personal";
	}

	/**
	 * @Title: personal
	 * @Description: TODO(查找个人基本资料的方法)
	 * @author: lzy
	 * @date: 2018年5月7日 下午1:21:29
	 */
	@GetMapping("/personal")
	@ResponseBody
	PageUtils personal(Model model) {
		int roleId = userRoleService.getByUserId(getUserId());
		UserDO userDO = useroldService.get(getUserId());
		if (roleId == Constant.ROLEADMIN_ID) {// 如果角色是管理员
			PersonalDO personal = new PersonalDO();
			personal.setMyGrade("管理员");
			personal.setMyUpper("无");
			personal.setUpperPhone("无");
			personal.setCoin(userDO.getWyzMoney() + "");
			personal.setAllCoin(userDO.getWyzAllmoney() + "");
			// 总的下级数量
			Map<String, Object> allmap = new HashMap<>();
			int newcount = userService.count(allmap);// 新系统下级数量
			int oldcount = useroldService.count(allmap);// 旧系统下级数量
			int allcount = newcount + oldcount;
			// 新系统客户的数量
			Map<String, Object> newmap = new HashMap<>();
			newmap.put("agencyRank", Constant.AGENT_USER);
			int newkcount = userService.count(newmap);
			// 旧系统客户的数量
			Map<String, Object> oldmap = new HashMap<>();
			int oldkcount = useroldService.iscount(oldmap);

			personal.setCount(allcount - (newkcount + oldkcount));
			personal.setKcount(newkcount + oldkcount);
			List<PersonalDO> list = new ArrayList<PersonalDO>();
			list.add(0, personal);
			model.addAttribute("userID", getUserId());
			PageUtils pageUtils = new PageUtils(list);
			return pageUtils;
		} else {
			PersonalDO personalDO = new PersonalDO();
			Long agencyRank = userDO.getAgencyRank();
			if (userDO.getMyupper() == 0 || userDO.getMyupper() == Constant.SQL_NUMBER) {
				personalDO.setMyUpper("速用科技");
				personalDO.setUpperPhone("请查看官网联系电话");
			} else {
				personalDO.setMyUpper(useroldService.get(userDO.getMyupper()).getCompanyName());
				personalDO.setUpperPhone(useroldService.get(userDO.getMyupper()).getPhone());

			}
			if (agencyRank == Constant.AGENT_ONE) {
				personalDO.setMyGrade("一级代理");
			} else if (agencyRank == Constant.AGENT_TWO) {
				personalDO.setMyGrade("二级代理");
			} else if (agencyRank == Constant.AGENT_THREE) {
				personalDO.setMyGrade("三级代理");
			} else if (agencyRank == 22) {
				personalDO.setMyGrade("合伙人");
			} else {
				personalDO.setMyGrade("客户");
			}
			personalDO.setCoin(userDO.getWyzMoney() + "");
			personalDO.setAllCoin(userDO.getWyzAllmoney() + "");

			// 总的下级数量
			Map<String, Object> allmap = new HashMap<>();
			allmap.put("myupper", getUserId());
			int newcount = userService.count(allmap);// 新系统下级数量
			int oldcount = useroldService.count(allmap);// 旧系统下级数量
			int allcount = newcount + oldcount;
			// 新系统客户的数量
			Map<String, Object> newmap = new HashMap<>();
			newmap.put("myupper", getUserId());
			newmap.put("agencyRank", Constant.AGENT_USER);
			int newkcount = userService.count(newmap);
			// 旧系统客户的数量
			Map<String, Object> oldmap = new HashMap<>();
			oldmap.put("myupper", getUserId());
			int oldkcount = useroldService.iscount(oldmap);

			personalDO.setCount(allcount - (newkcount + oldkcount));
			personalDO.setKcount(newkcount + oldkcount);
			List<PersonalDO> list = new ArrayList<PersonalDO>();
			list.add(0, personalDO);
			model.addAttribute("userID", getUserId());
			PageUtils pageUtils = new PageUtils(list);
			return pageUtils;
		}

	}

	@ResponseBody
	@PostMapping("/uploadImg")
	R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
		try {
			result = userService.updatePersonalImg(file, avatar_data, getUserId());
		} catch (Exception e) {
			return R.error("更新图像失败！");
		}
		if (result != null && result.size() > 0) {
			return R.ok(result);
		} else {
			return R.error("更新图像失败！");
		}
	}
	
	/**
	 * 
	 * @Title: viewAddress
	 * @Description: TODO(查看地址的方法)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年9月14日
	 */
	@ResponseBody
	@PostMapping("/viewAddress")
	R viewAddress(long id) {
		SuyongDO suyongDO = suyongService.get(id);
		if (suyongDO != null) {
			 String str = suyongDO.getProvince() + suyongDO.getCity() +suyongDO.getCity()+suyongDO.getLiveAddress();
             return R.ok(str);
		} else {
			return R.ok("该用户暂未记录地址");
		}


	}
	
	
	

	/**
	 * 
	 * @Title: stop
	 * @Description: TODO(开启状态的方法)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年4月26日
	 */
	@ResponseBody
	@PostMapping("/stop")
	R stop(long id) {
		try {
			UserDO user = new UserDO();
			user.setId(id);
			user.setStatus(1);
			userService.update(user);
			return R.ok();
		} catch (Exception e) {
			return R.error();
		}

	}

	/**
	 * 
	 * @Title: start
	 * @Description: TODO(关闭状态的方法)
	 * @return: R
	 * @author:liuziyu
	 * @date:2018年4月26日
	 */
	@ResponseBody
	@PostMapping("/start")
	R start(long id) {
		try {
			UserDO user = new UserDO();
			user.setId(id);
			user.setStatus(0);
			userService.update(user);
			return R.ok();
		} catch (Exception e) {
			return R.error();
		}
	}

	/**
	 * @param model
	 *            月业绩查询
	 */
	@ResponseBody
	@GetMapping("/payGetMonth")
	public Map<String, Object> payGetMonth(Model model) {
		long userId = ShiroUtils.getUserId();
		PayDO payDO = new PayDO();
		payDO.setUserId(userId);
		payDO.setStartDate(java.sql.Date.valueOf("2018-1-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-1-31"));
		List<PayDO> listPayDoOne = payService.listPayDo(payDO);
		int onePerformance = 0;
		for (PayDO payDO2 : listPayDoOne) {
			onePerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-2-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-2-28"));
		List<PayDO> listPayDoTow = payService.listPayDo(payDO);
		int towPerformance = 0;
		for (PayDO payDO2 : listPayDoTow) {
			towPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-3-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-3-31"));
		List<PayDO> listPayDoThree = payService.listPayDo(payDO);
		int threePerformance = 0;
		for (PayDO payDO2 : listPayDoThree) {
			threePerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-4-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-4-30"));
		List<PayDO> listPayDofour = payService.listPayDo(payDO);
		int fourPerformance = 0;
		for (PayDO payDO2 : listPayDofour) {
			fourPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-5-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-5-31"));
		List<PayDO> listPayDoFive = payService.listPayDo(payDO);
		int fivePerformance = 0;
		for (PayDO payDO2 : listPayDoFive) {
			fivePerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-6-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-6-30"));
		List<PayDO> listPayDoSix = payService.listPayDo(payDO);
		int sixPerformance = 0;
		for (PayDO payDO2 : listPayDoSix) {
			sixPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-7-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-7-31"));
		List<PayDO> listPayDoSeven = payService.listPayDo(payDO);
		int sevenPerformance = 0;
		for (PayDO payDO2 : listPayDoSeven) {
			sevenPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-8-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-8-31"));
		List<PayDO> listPayDoEight = payService.listPayDo(payDO);
		int eightPerformance = 0;
		for (PayDO payDO2 : listPayDoEight) {
			eightPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-9-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-9-30"));
		List<PayDO> listPayDoNine = payService.listPayDo(payDO);
		int ninePerformance = 0;
		for (PayDO payDO2 : listPayDoNine) {
			ninePerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-10-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-10-31"));
		List<PayDO> listPayDoTen = payService.listPayDo(payDO);
		int tenPerformance = 0;
		for (PayDO payDO2 : listPayDoTen) {
			tenPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-11-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-11-30"));
		List<PayDO> listPayDoEleven = payService.listPayDo(payDO);
		int elevenPerformance = 0;
		for (PayDO payDO2 : listPayDoEleven) {
			elevenPerformance += payDO2.getPaymoney();
		}

		payDO.setStartDate(java.sql.Date.valueOf("2018-12-1"));
		payDO.setEndDate(java.sql.Date.valueOf("2018-12-31"));
		List<PayDO> listPayDoTwelve = payService.listPayDo(payDO);
		int twelvePerformance = 0;
		for (PayDO payDO2 : listPayDoTwelve) {
			twelvePerformance += payDO2.getPaymoney();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("onePerformance", onePerformance);
		map.put("towPerformance", towPerformance);
		map.put("threePerformance", threePerformance);
		map.put("fourPerformance", fourPerformance);
		map.put("fivePerformance", fivePerformance);
		map.put("sixPerformance", sixPerformance);
		map.put("sevenPerformance", sevenPerformance);
		map.put("eightPerformance", eightPerformance);
		map.put("ninePerformance", ninePerformance);
		map.put("tenPerformance", tenPerformance);
		map.put("elevenPerformance", elevenPerformance);
		map.put("twelvePerformance", twelvePerformance);
		map.put("firstQuarter", onePerformance + towPerformance + threePerformance);
		map.put("secondQuarter", fourPerformance + fivePerformance + sixPerformance);
		map.put("threeQuarter", sevenPerformance + eightPerformance + ninePerformance);
		map.put("fourQuarter", tenPerformance + elevenPerformance + twelvePerformance);
		return map;
	}

	@GetMapping("/performanTemplate")
	public String performanTemplate(Model model) {

		return prefix + "/performanceList";
	}

	@ResponseBody
	@PostMapping("/clearcache")
	@CacheEvict(value = "app", key = "'performanceList'")
	public R clearcache() {

		return R.ok("清除成功！数据已更新");
	}

	/**
	 * 月度业绩列表
	 */
	@ResponseBody
	@Cacheable(value = "app", key = "'performanceList'")
	@GetMapping("/performanceList")
	public PageUtils payList(@RequestParam Map<String, Object> params, Model model) {
		List<MonthPerformance> payList = new LinkedList<MonthPerformance>();
		List<PayDO> list = payService.listPerformance();
		int count = 0;
		for (PayDO payDO1 : list) {
			count++;
			PayDO payDO = new PayDO();
			payDO.setUserId(payDO1.getUserId());
			payDO.setStartDate(java.sql.Date.valueOf("2018-1-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-1-31"));
			List<PayDO> listPayDoOne = payService.listPayDo(payDO);
			int onePerformance = 0;
			for (PayDO payDO2 : listPayDoOne) {
				onePerformance += payDO2.getPaymoney();
			}
			payDO.setStartDate(java.sql.Date.valueOf("2018-2-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-2-28"));
			List<PayDO> listPayDoTow = payService.listPayDo(payDO);
			int towPerformance = 0;
			for (PayDO payDO2 : listPayDoTow) {
				towPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-3-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-3-31"));
			List<PayDO> listPayDoThree = payService.listPayDo(payDO);
			int threePerformance = 0;
			for (PayDO payDO2 : listPayDoThree) {
				threePerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-4-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-4-30"));
			List<PayDO> listPayDofour = payService.listPayDo(payDO);
			int fourPerformance = 0;
			for (PayDO payDO2 : listPayDofour) {
				fourPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-5-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-5-31"));
			List<PayDO> listPayDoFive = payService.listPayDo(payDO);
			int fivePerformance = 0;
			for (PayDO payDO2 : listPayDoFive) {
				fivePerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-6-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-6-30"));
			List<PayDO> listPayDoSix = payService.listPayDo(payDO);
			int sixPerformance = 0;
			for (PayDO payDO2 : listPayDoSix) {
				sixPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-7-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-7-31"));
			List<PayDO> listPayDoSeven = payService.listPayDo(payDO);
			int sevenPerformance = 0;
			for (PayDO payDO2 : listPayDoSeven) {
				sevenPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-8-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-8-31"));
			List<PayDO> listPayDoEight = payService.listPayDo(payDO);
			int eightPerformance = 0;
			for (PayDO payDO2 : listPayDoEight) {
				eightPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-9-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-9-30"));
			List<PayDO> listPayDoNine = payService.listPayDo(payDO);
			int ninePerformance = 0;
			for (PayDO payDO2 : listPayDoNine) {
				ninePerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-10-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-10-31"));
			List<PayDO> listPayDoTen = payService.listPayDo(payDO);
			int tenPerformance = 0;
			for (PayDO payDO2 : listPayDoTen) {
				tenPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-11-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-11-30"));
			List<PayDO> listPayDoEleven = payService.listPayDo(payDO);
			int elevenPerformance = 0;
			for (PayDO payDO2 : listPayDoEleven) {
				elevenPerformance += payDO2.getPaymoney();
			}

			payDO.setStartDate(java.sql.Date.valueOf("2018-12-1"));
			payDO.setEndDate(java.sql.Date.valueOf("2018-12-31"));
			List<PayDO> listPayDoTwelve = payService.listPayDo(payDO);
			int twelvePerformance = 0;
			for (PayDO payDO2 : listPayDoTwelve) {
				twelvePerformance += payDO2.getPaymoney();
			}

			UserDO userDO = userService.get(payDO1.getUserId());
			MonthPerformance monthPerformance = new MonthPerformance();
			monthPerformance.setName(userDO.getCompanyName());
			monthPerformance.setOnePerformance(onePerformance);
			monthPerformance.setTowPerformance(towPerformance);
			monthPerformance.setThreePerformance(threePerformance);
			monthPerformance.setFourPerformance(fourPerformance);
			monthPerformance.setFivePerformance(fivePerformance);
			monthPerformance.setSixPerformance(sixPerformance);
			monthPerformance.setSevenPerformance(sevenPerformance);
			monthPerformance.setEightPerformance(eightPerformance);
			monthPerformance.setNinePerformance(ninePerformance);
			monthPerformance.setTenPerformance(tenPerformance);
			monthPerformance.setElevenPerformance(elevenPerformance);
			monthPerformance.setTwelvePerformance(twelvePerformance);
			payList.add(monthPerformance);
		}
		PageUtils pageUtil = new PageUtils(payList, count);
		return pageUtil;
	}

	/**
	 * @Title: mySelfGpsMap
	 * @Description: TODO(我的地图定位功能)
	 * @author: lzy
	 * @date: 2018年5月19日 下午4:39:54
	 */
	@GetMapping("/mySelfGpsMap")
	String mySelfGpsMap(Model model) {
		return prefix + "/mySelfGpsMap";
	}
	
	@ResponseBody
	@GetMapping("/mySelfGpsMapdemo")
	@Cacheable(value = "app", key = "'map'")
	public List<SuyongDO> mySelfGpsMapdemo(Model model) {
		List<SuyongDO> listAllUser = suyongService.listAll();
		List<SuyongDO> list = new ArrayList<SuyongDO>();
		for (SuyongDO suyongDO : listAllUser) {
			UserDO user = useroldService.get(suyongDO.getUserId());
			if (userRoleService.getByUserId(suyongDO.getUserId()) == Constant.ROLEAGENT_ID && user.getDelflag() == 0 && user.getAgencyRank() == Constant.AGENT_ONE ) {
				suyongDO.setCompanyName(user.getCompanyName());
				suyongDO.setPhone(user.getPhone());
				suyongDO.setAgencyName("一级代理");
				list.add(suyongDO);
			}else if (userRoleService.getByUserId(suyongDO.getUserId()) == Constant.ROLEAGENT_ID && user.getDelflag() == 0 && user.getAgencyRank() == Constant.AGENT_TWO ) {
				suyongDO.setCompanyName(user.getCompanyName());
				suyongDO.setPhone(user.getPhone());
				suyongDO.setAgencyName("二级代理");
				list.add(suyongDO);
			}else if (userRoleService.getByUserId(suyongDO.getUserId()) == Constant.ROLEAGENT_ID && user.getDelflag() == 0 && user.getAgencyRank() == Constant.AGENT_THREE ) {
				suyongDO.setCompanyName(user.getCompanyName());
				suyongDO.setPhone(user.getPhone());
				suyongDO.setAgencyName("三级代理");
				list.add(suyongDO);
			}

		}
	    return  list;
	}
	
	/**
	 * @Title: mySelfGpsMapPhone
	 * @Description: TODO(移动端我的地图定位功能)
	 * @author: lzy
	 * @date: 2018年5月19日 下午4:39:54
	 */
	@ResponseBody
	@GetMapping("/mySelfGpsMapPhone")
	List mySelfGpsMapPhone(String province) {
		List<SuyongDO> listAllUser = suyongService.listAllUser(province);
		for (SuyongDO suyongDO : listAllUser) {
			UserDO user = useroldService.get(suyongDO.getUserId());
			suyongDO.setCompanyName(user.getCompanyName());
			suyongDO.setPhone(user.getPhone());
		}
		return listAllUser;
	}

	/**
	 * 跳到第一次登陆添加地址页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("/firstLoginAddress")
	String firstLoginAddress(Model model) {
		return prefix + "/firstLoginAddress";
	}

	/**
	 * 保存第一次登陆是填写的地址
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping("/saveAddress")
	@ResponseBody
	R saveAddress(UserDO user) {
		UserDO olduser = useroldService.get(getUserId());
		olduser.setInviteCode(ShareCodeUtil.toSerialCode(getUserId()));
		olduser.setId(getUserId());
		olduser.setAgencyRank(olduser.getAgencyRank());
		// 新增旧系统角色
		UserRoleDO userRoleDO = new UserRoleDO();
		if (olduser.getAgencyRank() == Constant.AGENT_ONE || olduser.getAgencyRank() == Constant.AGENT_TWO
				|| olduser.getAgencyRank() == Constant.AGENT_THREE) {
			userRoleDO.setRoleId((long) 2);
		} else {
			userRoleDO.setRoleId((long) 3);
		}
		userRoleDO.setUserId(getUserId());

		userRoleService.save(userRoleDO);
		useroldService.update(olduser);
		SuyongDO suyongDO = new SuyongDO();
		suyongDO.setUserId(getUserId());
		if (olduser.getAgencyRank() == Constant.AGENT_ONE || olduser.getAgencyRank() == Constant.AGENT_TWO
				|| olduser.getAgencyRank() == Constant.AGENT_THREE) {
			suyongDO.setAuthNo(DateUtils.getOrderIdByTime());
		}
		suyongDO.setStatus(1);
		suyongDO.setCity(user.getCity());
		suyongDO.setDistrict(user.getDistrict());
		suyongDO.setProvince(user.getProvince());
		suyongDO.setLiveAddress(user.getLiveAddress());
		suyongDO.setFirstlogin(1);
		if (suyongService.save(suyongDO) > 0) {
			return R.ok("保存地址成功");
		}
		return R.error("保存地址失败");

	}

	/**
	 * @Title: appPersonal
	 * @Description: TODO(移动端个人详情页面)
	 * @author: lzy
	 * @date: 2018年5月26日 下午1:58:49
	 */
	@GetMapping("/appPersonal")
	@ResponseBody
	Map<String, Object> appPersonal() {
		UserDO user = (UserDO) SecurityUtils.getSubject().getPrincipal();
		try {
			UserDO userDO = userService.get(user.getId());
			int byUserId = userRoleService.getByUserId(user.getId());
			userDO.setRoleId(byUserId);
			Map<String, Object> map = new HashMap<>();
			map.put("msg", userDO);
			return map;
		} catch (Exception e) {
			return R.error("no");
		}

	}
	
	
	//通知封装方法
	
	public static NotifyDO setNotify(long CreateBy,String Title,String Content,String Remarks,long id){
		NotifyDO notify = new NotifyDO();
		notify.setCreateBy(CreateBy);
		notify.setTitle(Title);
		notify.setContent(Content);
		notify.setRemarks(Remarks);
		Long[] userIds = { id };
		notify.setUserIds(userIds);
		return  notify;
	}
	
	//速用币明细之注册送币封装方法
	public  int resDeatailsForSupport(long userId,Long sum,Long coin){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("邀请注册送速用币");
		payDeatailsDO.setDeatailsSupport(coin);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	
	//速用币明细之代理充值速用币增加封装方法
	public  int payDeatailsForSupport(long userId,Long amount,Long sum){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("代理充值速用币增加");
		payDeatailsDO.setDeatailsSupport(amount);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	//速用币明细之代理充值速用币减少封装方法
	public  int payDeatailsForExpend(long userId,Long amount,Long sum){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("代理充值速用币减少");
		payDeatailsDO.setDeatailsExpend(amount);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	
	//速用币明细之预存代理充值速用币增加封装方法
	public  int savaDeatailsForSupport(long userId,Long amount,Long sum){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("预存代理充值速用币增加");
		payDeatailsDO.setDeatailsSupport(amount);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	//速用币明细之预存代理充值速用币减少封装方法
	public  int savaDeatailsForExpend(long userId,Long amount,Long sum){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("预存代理充值速用币减少");
		payDeatailsDO.setDeatailsExpend(amount);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	
	//速用币明细之邀请送币增加封装方法
	public  int saveInviteForSupport(long userId,Long amount,Long sum){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("邀请用户累计充值速用币增加");
		payDeatailsDO.setDeatailsSupport(amount);
		payDeatailsDO.setSum(sum);
		int save = payDeatailsService.save(payDeatailsDO);
		return save;
	}
	
	
	
	
	//代理转移封装方法
	public  void autoAgent(long id,String name){
		//升级代理邀请用户自动转移  开始
			List<MyInviteDO> list = myInviteDao.get(id);
			for (MyInviteDO myInviteDO : list) {
				UserDO userDO = new UserDO();
				userDO.setId(myInviteDO.getInviteId());
				userDO.setMyupper(id);
				useroldService.update(userDO);
				
			}
			long id2 = useroldService.get(id).getMyupper();
			notifyService.save(setNotify(Constant.SQL_NUMBER, "重要通知", "您升级为代理,升级代理之前邀请的用户已自动转移至你的下级请注意查看", "请注意查看",id));
			notifyService.save(setNotify(Constant.SQL_NUMBER, "重要通知", "您的下级("+name+")升级为代理,("+name+")邀请的客户已自动转移至他的下级请注意查看", "请注意查看",id2));
		//升级代理邀请用户自动转移  结束
		
	}
	

}
